import React, {
    Component
} from "react";
import GridTable from '../../../components/display/gridTable';
import {
    findManagStubGroupList,
    prefixFile,
    updateStubStatus,
    stubRemoteUpdate
} from "../../../fetch/fetchApi";
import {
    Button,
    Input,
    Row,
    Col,
    Select,
    Divider,
    Modal,
    Form,
    Upload,
    Icon,
    Progress,
    DatePicker,
    message,
    Spin,
    Dropdown,
    Menu
} from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import moment from 'moment';
import AreaPicker from '../../../components/dataEntry/areaPicker';
import StubDetail from './stubDetail';
import OrderList from './orderList';
import StatusLog from './statusLog';
import {
    UpdateStatus,
    StubStatus
} from './updateStatus';
import RemoteUpgrade from './remoteUpgrade';
import UpgradeDetails from './upgradeDetails';
import UpgradeSuccessModal from './upgradeSuccessModal';

const Option = Select.Option;
const FormItem = Form.Item;
const {
    TextArea
} = Input;
const {
    RangePicker
} = DatePicker;

const deviceType = {
    "0": "交流电",
    "1": "直流电",
    "2": "交直流"
}
let selectedStubs = [];
class StubQuery extends Component {
    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {},
            loading: false,
            visible: false,
            selectedRowKeys: []
        };
    }

    componentDidMount() {
        this.fetch();
    }

    combineOptions = (json) => {
        if (!json) {
            return;
        }
        const options = [];
        for (let item in json) {
            options.push(<Option value={item}>{json[item]}</Option>);
        }
        return options;
    }

    init() {
        this.query = {
            page: 1,
            pagecount: 10
        };

        this.tableColumns = [{
            title: '电桩编号',
            dataIndex: 'stubId',
            fixed: 'left',
            width: 100
        }, {
            title: '所属城市',
            dataIndex: 'cityStr'
        }, {
            title: '所属电站',
            dataIndex: 'stubGroupName'
        }, {
            title: '设备类型',
            dataIndex: 'type',
            render: (text, record) => (
                <div>{deviceType[text] || "--"}</div>
            )
        }, {
            title: '最大功率',
            dataIndex: 'kw'
        }, {
            title: '当前状态',
            dataIndex: 'status',
            render: (text, record) => (
                <div>
                        {StubStatus[text] || `未知(${text})`}
                    </div>
            )
        }, {
            title: '型号',
            dataIndex: 'modelNo'
        }, {
            title: '固件型号',
            dataIndex: 'typeId'
        }, {
            title: '固件版本',
            dataIndex: 'frameWork',
            render: (text) => (
                <div>{(text === "null" || text === "NULL") ? "" : text}</div>
            )
        }, {
            title: '操作',
            key: 'operation',
            fixed: 'right',
            width: 300,
            render: (text, record) => (
                <div style={{width: 300}}>
                    <a href="javascript:void(0);" onClick={(e) => this.showDetailModal(record.stubGroupId)}>电站详情</a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={(e) => this.showOrderListModal(record.stubId)}>订单列表</a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={(e) => this.showStatusLogModal(record.stubId)}>状态日志</a>
                    <br/>
                    <a href="javascript:void(0);" onClick={(e) => this.showUpdateStatusModal(record.status, record.stubId)}>修改状态</a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={(e) => this.showRemoteUpgradeModal({
                            stubIds: record.stubId,
                            modelNos: record.modelNo
                        })}>远程升级
                    </a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={(e) => this.showUpgradeDetailsModal(record.stubId)}>升级履历</a>
                    <Divider type="vertical" />
                    <a href="javascript:void(0);" onClick={() => this.openTab({
                            'keyId': `stubParamsConfig${record.stubId}`,
                            'stubRecord': record
                        }, {
                            'key': 'stubParamsConfig',
                            titleText: '参数配置'
                        })}>配置信息
                    </a>
                </div>
            )
        }];

    }

    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    showDetailModal = (stubGroupId) => {
        this.setState({
            stubVisible: true,
            stubGroupId: stubGroupId
        })
    }

    showOrderListModal = (stubId) => {
        this.setState({
            orderListVisible: true,
            stubId: stubId
        })
    }

    showStatusLogModal = (stubId) => {
        this.setState({
            statusLogVisible: true,
            stubId: stubId
        })
    }

    showUpdateStatusModal = (status, stubId) => {
        this.currentStubId = stubId;
        this.currentStatus = status;
        this.setState({
            updateStatusVisible: true,
            currentStatus: status
        })
    }

    showRemoteUpgradeModal = (params = {}) => {
        if (!params.stubIds) {
            message.error("桩编号为空！");
            return;
        }
        this.setState({
            remoteUpgradeVisible: true,
            remoteUpgradeParams: {
                stubIds: params.stubIds,
            }
        })
    }

    showUpgradeDetailsModal = (stubId) => {
        this.setState({
            upgradeDetailsVisible: true,
            stubId: stubId
        })
    }

    async findManagStubGroupList() {
        return await findManagStubGroupList(this.query);
    }

    queryHandler = () => {
        this.query["page"] = 1;
        this.setState({
            selectedRowKeys: []
        })
        selectedStubs = [];
        this.fetch();
    }

    fetch = (params = {}) => {
        this.setState({
            loading: true
        });
        this.findManagStubGroupList().then((res) => {
            if (!res) {
                return;
            }
            const pagination = this.state.pagination;
            pagination.total = res.data.pageLimit.totalCount;
            pagination.current = params.current || 1;
            pagination.onChange = (page, pageSize) => {
                this.query["page"] = page;
                this.query["pagecount"] = pageSize;
                this.fetch({
                    current: page
                });
            }
            let dataSource = res.data.data;
            let startRowNo = res.data.pageLimit.startRowNo;
            for (let item of dataSource) {
                item["key"] = startRowNo;
                startRowNo++;
            }
            this.setState({
                loading: false,
                data: dataSource,
                pagination
            });
        }).catch((ex) => {
            console.log(ex);
        });
    }

    handleStatusChange = (e) => {
        if (e === "-1") {
            this.query["status"] = "";
        } else {
            this.query["status"] = e;
        }
    }

    handleInputChange = (type, e) => {
        this.query[type] = e.target.value;
    }

    handleCityChange = (e) => {
        console.log(e);
        if (e[1]) {
            this.query["city"] = e[1];
        } else {
            this.query["city"] = "";
        }
    }

    handleExport = () => {
        let excelUrl = prefixFile + '/export.do?serviceName=stubQuery&fileName=电桩查询&searchJson=';
        let paramUrl = '{';
        Object.keys(this.query).map((key) => {
            paramUrl += `"${key}"` + ":" + `"${this.query[key]}"` + ","
        });
        if (paramUrl.length > 0) {
            paramUrl = paramUrl.substr(0, paramUrl.length - 1)
        }
        paramUrl += "}";
        console.log(paramUrl);
        window.location.href = excelUrl + paramUrl;
    }

    handleStubModalCancel = (e) => {
        this.setState({
            stubVisible: false
        })
    }

    handleOrderListModalCancel = (e) => {
        this.setState({
            orderListVisible: false
        })
    }

    handleStatusLogCancel = (e) => {
        this.setState({
            statusLogVisible: false
        })
    }

    handleUpdateStatusCancel = (e) => {
        this.setState({
            updateStatusVisible: false
        })
    }

    handleUpdateStatusOk = (e) => {
        this.setState({
            updateStatusConfirmLoading: true,
            currentStatus: this.currentStatus
        })
        const res = updateStubStatus({
            stubId: this.currentStubId,
            status: this.currentStatus
        })
        res.then((data) => {
            if (data.data.code === "200") {
                this.handleUpdateStatusCancel();
                this.fetch();
            }
            this.setState({
                updateStatusConfirmLoading: false
            })
        }).catch((ex) => {
            console.log(ex);
            this.setState({
                updateStatusConfirmLoading: false
            })
        })
    }

    handleOrderList = (e) => {
        this.handleOrderListModalCancel();
    }

    handleUpdateStatus = (e) => {
        this.currentStatus = e;
    }

    handleRemoteUpgrade = (e) => {
        this.upgradeParams = e;
    }

    handleRemoteUpgradeOk = (e) => {
        if (JSON.stringify(this.upgradeParams) === "{}") {
            message.error("参数缺失");
            return;
        }
        this.setState({
            remoteUpgradeConfirmLoading: true
        });
        stubRemoteUpdate(this.upgradeParams).then((data) => {
            if (data.data.code === '200') {
                message.success("操作成功");
                this.setState({
                    upgradeSuccessModalVisible: true,
                    selectedRowKeys: []
                })
                selectedStubs = [];
            } else {
                console.log(data);
            }
            this.setState({
                remoteUpgradeConfirmLoading: false,
                remoteUpgradeVisible: false
            });
        }).catch((ex) => {
            console.log(ex);
            message.error("接口异常！");
            this.setState({
                remoteUpgradeConfirmLoading: false
            });
        })
    }

    handleRemoteUpgradeCancel = (e) => {
        this.setState({
            remoteUpgradeVisible: false
        })
    }

    handleUpgradeDetailsCancel = (e) => {
        this.setState({
            upgradeDetailsVisible: false
        })
    }

    handleMenuClick = (e) => {
        console.log(selectedStubs);
        //if (JSON.stringify(selectedStubs) === "{}") {
        if (selectedStubs.length === 0) {
            message.error("请至少选择一项");
            return;
        }
        let stubIds = "";
        let modelNos = "";
        for (let item of selectedStubs) {
            stubIds = stubIds + item.stubId + ",";
            modelNos = modelNos + item.modelNo + ",";
        }
        stubIds = stubIds.substring(0, stubIds.length - 1);
        modelNos = modelNos.substring(0, modelNos.length - 1);
        this.showRemoteUpgradeModal({
            stubIds: stubIds,
            modelNos: modelNos
        });
    }

    handleUpSuccessModalCancel = () => {
        this.setState({
            upgradeSuccessModalVisible: false
        })
    }

    handleStubDetail = () => {
        this.setState({
            stubGroupId: ""
        })
    }

    render() {
        const formItemLayout = {
            wrapperCol: {
                span: 16,
                offset: 4
            }
        };

        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys
                });
            },
            onSelect: (record, selected, selectedRows, nativeEvent) => {
                if (selected) {
                    selectedStubs.push(record);
                } else {
                    selectedStubs.map((item, key) => {
                        if (item.key === record.key) {
                            selectedStubs.splice(key, 1);
                        }
                    })
                }
            },
            onSelectAll: (selected, selectedRows, changeRows) => {
                if (selected) {
                    selectedStubs.push(...changeRows);
                } else {
                    changeRows.map((item, key) => {
                        selectedStubs.map((item1, key1) => {
                            if (item1.key === item.key) {
                                selectedStubs.splice(key1, 1);
                            }
                        })
                    })
                }
            }
        };

        const menu = (
            <Menu onClick={this.handleMenuClick}>
                <Menu.Item key="1">远程升级</Menu.Item>
            </Menu>
        );

        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={4} xl={4} className="whole-fill">
                        <Input placeholder="电桩编号精确查询" onChange={(e) => this.handleInputChange("stubId", e)}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="电站名称查询" onChange={(e) => this.handleInputChange("stubGroupName", e)}/>
                    </Col>
                    <Col lg={3} xl={3}>
                        <AreaPicker pickAreaHandler={this.handleCityChange}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="设备型号" onChange={(e) => this.handleInputChange("modelNo", e)}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="固件型号" onChange={(e) => this.handleInputChange("typeId", e)}/>
                    </Col>
                    <Col lg={4} xl={4} className="whole-fill">
                        <Input placeholder="固件版本精确查询" onChange={(e) => this.handleInputChange("frameWork", e)}/>
                    </Col>
                    { /*<Col lg={3} xl={3} className="whole-fill">
                        <Select placeholder="状态" onChange={this.handleStatusChange} defaultValue="-1">
                            {this.combineOptions(StubStatus)}
                        </Select>
                    </Col>*/ }
                    <div  className="button-inlineBlock" style={{'width': '120px'}}>
                        <Button type="primary" onClick={this.queryHandler}>查询</Button>
                    </div>
                    <div  className="button-inlineBlock" style={{'width': '120px'}}>
                        <Button type="primary" onClick={this.handleExport}>导出</Button>
                    </div>
                    <div  className="button-inlineBlock" style={{'width': '120px'}}>
                        <Dropdown overlay={menu}>
                            <Button type="primary">
                                更多 <Icon type="down" />
                            </Button>
                        </Dropdown>
                    </div>
                </Row>
            </div>
            <div className="page-panel">
                <GridTable rowSelection={rowSelection} postyle="table-center" data={this.state.data} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
            <Modal width="800px" title="电站详情" visible={this.state.stubVisible} footer={null} onCancel={this.handleStubModalCancel}>
                <StubDetail stubGroupId={this.state.stubGroupId} handle={this.handleStubDetail}/>
            </Modal>
            <Modal width="800px" title="订单列表" visible={this.state.orderListVisible} footer={null} onCancel={this.handleOrderListModalCancel}>
                <OrderList stubId={this.state.stubId} onAdd={this.props.onAdd} handle={this.handleOrderList}/>
            </Modal>
            <Modal width="800px" title="状态日志" visible={this.state.statusLogVisible} footer={null} onCancel={this.handleStatusLogCancel}>
                <StatusLog stubId={this.state.stubId} />
            </Modal>
            <Modal title="修改状态" visible={this.state.updateStatusVisible} confirmLoading={this.state.updateStatusConfirmLoading} onOk={this.handleUpdateStatusOk} onCancel={this.handleUpdateStatusCancel}>
                <UpdateStatus currentStatus={this.state.currentStatus} handle={this.handleUpdateStatus}/>
            </Modal>
            <Modal title="远程升级" visible={this.state.remoteUpgradeVisible} confirmLoading={this.state.remoteUpgradeConfirmLoading} onOk={this.handleRemoteUpgradeOk} onCancel={this.handleRemoteUpgradeCancel}>
                <RemoteUpgrade params={this.state.remoteUpgradeParams} handle={this.handleRemoteUpgrade} />
            </Modal>
            <Modal width="800px" title="升级履历" visible={this.state.upgradeDetailsVisible} footer={null} onCancel={this.handleUpgradeDetailsCancel}>
                <UpgradeDetails stubId={this.state.stubId} />
            </Modal>
            <UpgradeSuccessModal onAdd={this.props.onAdd} handleCancel={this.handleUpSuccessModalCancel} visible={this.state.upgradeSuccessModalVisible}/>
        </div>;

        return Content;
    }
}

export default StubQuery;